package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjy.dto.DictDTO;
import com.ktjy.mapper.SysDictTypeMapper;
import com.ktjy.pojo.SysDictType;
import com.ktjy.service.SysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {
    @Autowired
    private SysDictTypeMapper sysDictTypeMapper;

    /**
     * 分页查询字典类型
     *
     * @param dictDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public IPage<SysDictType> findPage(DictDTO dictDTO, Integer pageNo, Integer pageSize) {
        //构造分页插件
        Page<SysDictType> page = new Page(pageNo, pageSize);
        return sysDictTypeMapper.findPage(page, dictDTO);
    }

    /**
     * 保存或修改字典类型
     *
     * @param sysDictType
     */
    @Override
    public void saveOrUpdateDict(SysDictType sysDictType) {
        Long dictId = sysDictType.getDictId();
        LocalDateTime now = LocalDateTime.now();

        if (dictId != null ) {
            // 修改：只设置更新时间
            sysDictType.setUpdateTime(now);
        } else {
            // 新增：设置创建时间和更新时间
            sysDictType.setCreateTime(now);
            sysDictType.setUpdateTime(now);
        }

        // 只执行一次保存操作（根据dictId自动判断新增/修改）
        this.saveOrUpdate(sysDictType);
    }

    /**
     * 批量删除字典类型
     *
     * @param dictIds
     */
    @Override
    public void delBatchDict(Long[] dictIds) {
        // 检查字典类型ID数组是否为空
        if (dictIds.length > 0) {
            // 构造删除条件，根据字典类型ID进行批量删除
            QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("dict_id", dictIds);
            sysDictTypeMapper.delete(queryWrapper);
        } else {
            // 字典类型ID为空时抛出异常
            throw new IllegalArgumentException("字典类型ID不能为空");
        }
    }

    /**
     * 根据ID查询字典类型
     * @param id
     * @return
     */
    @Override
    public SysDictType findDict(Long id) {
        // 根据ID查询字典类型
        SysDictType sysDictType = sysDictTypeMapper.selectById(id);
        // 检查字典类型是否为空
        if (sysDictType != null) {
            // 字典类型不为空时返回字典类型
            return sysDictType;
        }
        return null;
    }

    /**
     * 查询字典类型列表
     * @param dictDTO
     * @return
     */
    @Override
    public List<SysDictType> findList(DictDTO dictDTO) {
        return sysDictTypeMapper.selectFile(dictDTO);
    }

    /**
     * 导出字典类型列表
     * @param title 标题
     * @param list
     * @return
     */
    @Override
    public Workbook exportExcel(String title, List<SysDictType> list) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建样式
        CellStyle headerStyle = workbook.createCellStyle();
        CellStyle dataStyle = workbook.createCellStyle();

        // 设置表头样式：加粗、居中
        Font headerFont = workbook.createFont();
        headerFont.setBold(true); // 加粗
        headerStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        headerStyle.setFont(headerFont);

        // 设置数据行样式：居中对齐
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建工作表
        Sheet sheet = workbook.createSheet(title);
        sheet.setColumnWidth(0, 4000);
        sheet.setColumnWidth(1, 4000);
        sheet.setColumnWidth(2, 4000);
        sheet.setColumnWidth(3, 4000);
        sheet.setColumnWidth(4, 4000);
        sheet.setColumnWidth(5, 4000);

        // 创建行
        Row row = sheet.createRow(0);
        // 创建列
        String[] titles = {"字典ID", "字典名称", "字典类型", "状态", "备注", "创建时间"};
        for (int i = 0; i < titles.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(headerStyle); // 应用表头样式
        }

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 创建数据行
        for (int i = 0; i < list.size(); i++) {
            SysDictType sysDictType = list.get(i);
            Row dataRow = sheet.createRow(i + 1);

            // 字典ID列
            Cell cell0 = dataRow.createCell(0);
            cell0.setCellValue(sysDictType.getDictId());
            cell0.setCellStyle(dataStyle);

            // 字典名称列
            Cell cell1 = dataRow.createCell(1);
            cell1.setCellValue(sysDictType.getDictName());
            cell1.setCellStyle(dataStyle);

            // 字典类型列
            Cell cell2 = dataRow.createCell(2);
            cell2.setCellValue(sysDictType.getDictType());
            cell2.setCellStyle(dataStyle);

            // 状态列
            Cell cell3 = dataRow.createCell(3);
            cell3.setCellValue(sysDictType.getStatus().equals("0") ? "正常" : "停用");
            cell3.setCellStyle(dataStyle);

            // 备注列
            Cell cell4 = dataRow.createCell(4);
            cell4.setCellValue(sysDictType.getRemark());
            cell4.setCellStyle(dataStyle);

            // 创建时间列
            Cell cell5 = dataRow.createCell(5);
            String createTimeStr = "";
            if (sysDictType.getCreateTime() != null) {
                createTimeStr = sysDictType.getCreateTime().format(dateTimeFormatter);
            }
            cell5.setCellValue(createTimeStr);
            cell5.setCellStyle(dataStyle);
        }
        return workbook;
    }

}
